package com.Tcp.Dome1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 客户端
 */
public class Socketdome {
	public static void main(String[] args) {
		PrintWriter out = null;
		String msg = null;
		Socket client = null;
		try {
			// 创建一个socket连接，并且指定IP及端口
			// 127.0.0.1
			// localhost
			client = new Socket("127.0.0.1", 8080);
			// 判断socket连接是否连接成功
			if (client != null) {
				System.out.println("已连接" + client.getLocalAddress().getHostName() + "服务器端");

				// 开启一个新的线程，去读取socket的内容
				new Thread(new ReadFromSocketThread(client)).start();

				// 使用client.getOutputStream()方法，获取连接的输出流，并且封闭进PrintWriter
				out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
				// 写内容至socket
				readFromCMD(client, out);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.println("EXIT");
			out.flush();
			out.close();
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void readFromCMD(Socket client, PrintWriter out) {
		// 读取命令行的输入
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();

		while (!"EXIT".equals(input)) {
			File file = new File(input);
			BufferedReader br;
			try {
				br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
				String str="";				
				while ((str = br.readLine()) != null) {
					out.println(str);
					out.flush();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		scanner.close();
	}

}

class ReadFromSocketThread implements Runnable {

	private Socket client;

	public ReadFromSocketThread(Socket client) {
		this.client = client;
	}

	@Override
	public void run() {
		BufferedReader br;
		try {
			br = new BufferedReader(new InputStreamReader(client.getInputStream()));
			while (true) {
				String str = br.readLine();
				System.out.println(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
